package net.jxtz.jxtzos.authentication.weixin;

import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.authentication.exception.NotFoundWechatUserInfoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 *
 * 微信登陆校验处理器
 * @author a123
 */

@Slf4j
@Component
public class WechatAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String unionId = authentication.getCredentials().toString();

        final WechatUserDetails userDetails = (WechatUserDetails)wechatUserDetailService.loadUserByUsername(unionId);
        if (Objects.isNull(userDetails)){
            String s = "微信用户校验失败";
            log.error(s);
            throw new NotFoundWechatUserInfoException(s);
        }

        String s = "微信用户校验成功";
        log.info(s);
        return new UsernamePasswordAuthenticationToken(userDetails, unionId, userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    private WechatUserDetailServiceImpl wechatUserDetailService;

    @Autowired
    private void setWechatUserDetailService(WechatUserDetailServiceImpl wechatUserDetailService){
        this.wechatUserDetailService = wechatUserDetailService;
    }
}
